package com.cxc.news.controller;

import com.cxc.news.pojo.User;
import com.cxc.news.service.UserService;
import com.cxc.news.utils.MD5Utils;
import com.cxc.news.utils.Value;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 返回登录页面视图
     * @return
     */
    @GetMapping("/logins")
    public String goToLogin(){
        return Value.PATH_LOGIN;
    }

    /**
     * 返回注册页面
     * @return
     */
    @GetMapping("/registers")
    public String goToRegister(){
        return Value.PATH_REGISTER;
    }


    /**
     * 登录
     * @param username
     * @param password
     * @param request
     * @return
     */
    @PostMapping("/login")
    public String login(String username, String password, HttpServletRequest request,Map map){
        User user = userService.checkUser(username,password);

        if (user != null){
            request.getSession().setAttribute("user",user);
            //重定向到主页
            return Value.REDIRECT_PATH_INDEX;
        }
        return Value.PATH_LOGIN;
    }

    /**
     * 注册
     * @param user
     * @param map
     * @return
     */
    @PostMapping("/register")
    public String register(User user, Map map){
        User user1 = userService.getUserByName(user.getUsername());
        if (user1 != null){
            map.put("message","用户名已存在,请重新选择");
            return Value.PATH_REGISTER;
        }
        user.setAvatar("...");
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setPassword(MD5Utils.code(user.getPassword()));
        user.setType(1);
        userService.addUser(user);
        return Value.PATH_LOGIN;
    }

    /**
     * 登出
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        if (user != null){
            request.getSession().removeAttribute("user");
        }
        return Value.REDIRECT_PATH_INDEX;
    }

    @RequestMapping("/deluser/{id}")
    public String deleteUser(@PathVariable("id") Long id){
        userService.deleteUser(id);
        return "redirect:/admin/-1";
    }

}
